package com.zxlfysj.stack;

/**
 * 使用数组实现栈
 * @author yangshujing
 * @create 2020-08-16 18:33
 */
public class ArrayStackDemo {
    public static void main(String[] args) {

        ArrayStack stack  = new ArrayStack(4);
        //测试
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.list();
        System.out.println(stack.pop());
        stack.list();

    }
}

class ArrayStack {
    private int maxSize; //栈的大小
    private int[] stack; //使用数组模拟栈
    private int top = -1; //栈顶

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
    }

    //判断栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    //判断栈空
    public boolean isEmpty() {
        return top == -1;
    }

    //入栈
    public void push(int value) {
        if(isFull()) {
            System.out.println("栈已满");
            return;
        }
        top++;
        stack[top] = value;
    }

    //出栈
    public int pop() {
        if(isEmpty()) {
            throw new RuntimeException("栈空");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //遍历
    public void list() {
        if(isEmpty()) {
            System.out.println("栈空");
            return;
        }
        for(int i = top; i >= 0; i--) {
            System.out.printf("stack[%d] = %d \n", i, stack[i]);
        }
    }
}
